package com.ruoyi.project.warehouseSystem.service.impl;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.domain.server.TreeSelectComptClassify;
import com.ruoyi.project.warehouseSystem.domain.ComptClassify;
import com.ruoyi.project.warehouseSystem.mapper.ComptClassifyMapper;
import com.ruoyi.project.warehouseSystem.mapper.DocumentClassifyMapper;
import com.ruoyi.project.warehouseSystem.service.IComptClassifyService;
import com.ruoyi.project.warehouseSystem.service.IDocumentClassifyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 档案分类Service业务层处理
 * 
 * @author wangshuo
 * @date 2021-01-22
 */
@Service
public class DocumentClassifyServiceImpl implements IDocumentClassifyService
{
    @Autowired
    private ComptClassifyMapper comptClassifyMapper;

    @Autowired
    private DocumentClassifyMapper documentClassifyMapper;

    /**
     * 查询档案分类
     * 
     * @param id 档案分类ID
     * @return 档案分类
     */
    @Override
    public ComptClassify selectComptClassifyById(Long id)
    {
        return documentClassifyMapper.selectComptClassifyById(id);
    }

    /**
     * 查询档案分类列表
     * 
     * @param comptClassify 档案分类
     * @return 档案分类
     */
    @Override
    public List<ComptClassify> selectComptClassifyList(ComptClassify comptClassify)
    {
        return documentClassifyMapper.selectComptClassifyList(comptClassify);
    }

    /**
     * 新增档案分类
     * 
     * @param comptClassify 档案分类
     * @return 结果
     */
    @Override
    @Transactional
    public int insertComptClassify(ComptClassify comptClassify)
    {
        if (UserConstants.NOT_UNIQUE.equals(this.checkComptClassNameUnique(comptClassify))){
         throw new BaseException("新增区域'" + comptClassify.getClassifyName() + "'失败，区域名称已存在");
        }
        if(comptClassify.getParentId()==null){
            //第一次新增ancestors = 0
            comptClassify.setAncestors("0");
            comptClassify.setParentId(0L);
        }else {
            ComptClassify comptClassify1 = documentClassifyMapper.selectComptClassifyById(comptClassify.getParentId());
            comptClassify.setAncestors(comptClassify1.getAncestors()+","+comptClassify1.getId());
        }
        comptClassify.setCreateBy(SecurityUtils.getUsername());
        comptClassify.setGmtCreate(new Date());
        int i = documentClassifyMapper.insertComptClassify(comptClassify);
        //分类编号
        if(i>0){
            String str = "archives" + String.format("%06d", comptClassify.getId());
            comptClassify.setClassifySn(str);
            documentClassifyMapper.updateComptClassify(comptClassify);
        }
        return i;
    }

    private String checkComptClassNameUnique(ComptClassify comptClassify) {
        Long id = StringUtils.isNull(comptClassify.getId()) ? -1L : comptClassify.getId();
        ComptClassify info = documentClassifyMapper.checkComptClassNameUnique(comptClassify.getClassifyName(), comptClassify.getParentId());
        if (StringUtils.isNotNull(info) && info.getId().longValue() != id.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 修改档案分类
     * 
     * @param comptClassify 档案分类
     * @return 结果
     */
    @Override
    @Transactional
    public int updateComptClassify(ComptClassify comptClassify)
    {
        if (UserConstants.NOT_UNIQUE.equals(this.checkComptClassNameUnique(comptClassify)))
        {
            throw new BaseException("修改分类'" + comptClassify.getClassifyName() + "'失败，分类名称已存在");
        }
        else if (comptClassify.getParentId().equals(comptClassify.getId()))
        {
            throw new BaseException("修改分类'" + comptClassify.getClassifyName() + "'失败，上级区域不能是自己");
        }
        ComptClassify comptClassify1 = documentClassifyMapper.selectComptClassifyById(comptClassify.getParentId());
        comptClassify.setAncestors(comptClassify1.getAncestors()+","+comptClassify1.getId());
        comptClassify.setModifyBy(SecurityUtils.getUsername());
        comptClassify.setGmtModify(new Date());
        return documentClassifyMapper.updateComptClassify(comptClassify);
    }

    /**
     * 批量删除档案分类
     * 
     * @param ids 需要删除的档案分类ID
     * @return 结果
     */
    @Override
    public int deleteComptClassifyByIds(Long[] ids)
    {
        return documentClassifyMapper.deleteComptClassifyByIds(ids);
    }

    /**
     * 删除档案分类信息
     * 
     * @param id 档案分类ID
     * @return 结果
     */
    @Override
    public int deleteComptClassifyById(Long id)
    {
        return documentClassifyMapper.deleteComptClassifyById(id);
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelectComptClassify> buildComptClassifyTreeSelect(List<ComptClassify> comptClassifies)
    {
        List<ComptClassify> comptClassifyTrees = buildComptClassifyTree(comptClassifies);
        return comptClassifyTrees.stream().map(TreeSelectComptClassify::new).collect(Collectors.toList());
    }

    /**
     * 构建前端所需要树结构
     *
     * @param
     * @return 树结构列表
     */
    @Override
    public List<ComptClassify> buildComptClassifyTree(List<ComptClassify> comptClassifies)
    {
        List<ComptClassify> returnList = new ArrayList<>();
        List<Long> tempList = new ArrayList<Long>();
        for (ComptClassify comptClassify : comptClassifies)
        {
            tempList.add(comptClassify.getId());
        }
        for (Iterator<ComptClassify> iterator = comptClassifies.iterator(); iterator.hasNext();)
        {
            ComptClassify comptClassify = (ComptClassify) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(comptClassify.getParentId()))
            {
                recursionFn(comptClassifies, comptClassify);
                returnList.add(comptClassify);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = comptClassifies;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<ComptClassify> list, ComptClassify t)
    {
        // 得到子节点列表
        List<ComptClassify> childList = getChildList(list, t);
        t.setChildren(childList);
        for (ComptClassify tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                // 判断是否有子节点
                Iterator<ComptClassify> it = childList.iterator();
                while (it.hasNext())
                {
                    ComptClassify n = (ComptClassify) it.next();
                    recursionFn(list, n);
                }
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<ComptClassify> getChildList(List<ComptClassify> list, ComptClassify t)
    {
        List<ComptClassify> tlist = new ArrayList<>();
        Iterator<ComptClassify> it = list.iterator();
        while (it.hasNext())
        {
            ComptClassify n = (ComptClassify) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<ComptClassify> list, ComptClassify t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }
}
